//
//  SeekExactBaseView.m
//  cityCar
//
//  Created by yao on 14-10-29.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SeekExactBaseView.h"
#import "SeekInToCell.h"
#import "Connection.h"
#import "ExactModel.h"
#import "SeekExactReusableView.h"
#import "WebColor.h"
#import "SeekCarViewController.h"


@interface SeekExactBaseView ()
// 存放四个不限
@property (nonatomic, retain) NSMutableArray *indexPathArr;

@end
@implementation SeekExactBaseView

- (void)dealloc
{
    [_arrSection release];
    [_arrRow release];
    [_array release];
    [_collectionView release];
    [_dicc release];
    [_dictionary release];
    [_string release];
    [_button release];
    [_indexPathArr release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.dicc       = [NSMutableDictionary dictionary];
        self.array      = [NSMutableArray array];
        self.arrSection = [NSMutableArray array];
        self.arrRow     = [NSMutableArray array];
        self.dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"0", @"jiage", @"0", @"jibie", @"0", @"pailiang", @"0", @"biansuxiang", nil];
        self.string     = [NSMutableString string];
        self.indexPathArr = [NSMutableArray array];
        
    }
    return self;
}
// 存放4个不限cell的位置indexpath
- (void)initIndexPathArr
{
    self.indexPathArr = [NSMutableArray array];
    for (int i = 0; i < 4; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:i];
        [self.indexPathArr addObject:indexPath];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self startConnection];
    [self setupSubviews];
}
- (void)setupSubviews
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.frame.size.width / 3 - 10, 30);
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    flowLayout.headerReferenceSize = CGSizeMake(self.frame.size.width, 25);
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.frame collectionViewLayout:flowLayout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate   = self;
    [self addSubview:self.collectionView];
    [_collectionView registerClass:[SeekInToCell class] forCellWithReuseIdentifier:@"xuanche"];
    
    [self.collectionView registerClass:[SeekExactReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"xxx"];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView release];
    self.button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    self.button.frame = CGRectMake(30, self.frame.size.height - 60, self.frame.size.width - 60, 30);
    self.button.backgroundColor = [WebColor lightBlue];
    
    [self.button addTarget:self action:@selector(buttonClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    [self addSubview:self.button];
    self.button.hidden = YES;
}
- (void)buttonClicked:(UIButton *)button
{
    // 把存放4个value的字典从当前的view 传到 SeekCarViewController
    self.blockValue(_dictionary);
    
}
- (void)startConnection
{
    // 精准选车的数据解析
    [Connection networkHandlerWith:@"http://mrobot.pcauto.com.cn/v3/price/models/criterionv36?v=4.3.0" block:^(id result) {
        // 把价格、排量、等放到数组arr里
        NSMutableArray *arr = [result objectForKey:@"criterion"];
        // 取arr里前四项
        for (int j = 0; j < 4; j++) {
            [self.array addObject:arr[j]];
        }
        // 把section名字存到arrsection里
        for (NSMutableDictionary *dic1 in self.array) {
            NSMutableString *str = [dic1 objectForKey:@"name"];
            [self.arrSection addObject:str];
        }
        // 使arrSection里的每个name对应cell数组 并将他们放到字典self.dicc里
        for (int i = 0; i < self.arrSection.count; i++) {
            self.arrRow = [NSMutableArray array];
            for (NSMutableDictionary *dic2 in [[self.array objectAtIndex:i] objectForKey:@"cris"]) {
                ExactModel *model = [[ExactModel alloc] init];
                model.name  = [dic2 objectForKey:@"name"];
                model.value = [dic2 objectForKey:@"value"];
                [self.arrRow addObject:model];
            }
            [self.dicc setValue:self.arrRow forKey:self.arrSection[i]];
        }
        [self initIndexPathArr];
        [_collectionView reloadData];
    }];
}
- (void)startConnect
{
    // 解析出有多少辆车符合要求
    NSMutableString *str = [NSMutableString stringWithFormat:@"http://mrobot.pcauto.com.cn/v2/price/models/search?price=%@&jb=%@&pl%@&bsx=%@&pageNo=1&pageSize=20&v=4.3.0", [self.dictionary objectForKey:@"jiage"], [self.dictionary objectForKey:@"jibie"], [self.dictionary objectForKey:@"pailiang"], [self.dictionary objectForKey:@"biansuxiang"]];
    [Connection networkHandlerWith:str block:^(id result) {
        self.string = [NSMutableString stringWithFormat:@"%@辆车符合条件，点击查看",[result objectForKey:@"total"]];
        NSLog(@"%@", self.string);
        if ([self.string isEqualToString:@"0辆车符合条件，点击查看"]) {
            self.button.userInteractionEnabled = NO;
            [self.button setTitle:@"没有符合条件的车" forState:UIControlStateNormal];
            self.button.backgroundColor = [WebColor gray];
            self.button.titleLabel.textColor = [WebColor whiteSmoke];
        } else {
            self.button.userInteractionEnabled = YES;
        [self.button setTitle:self.string forState:UIControlStateNormal];
            self.button.backgroundColor = [WebColor lightBlue];
            self.button.titleLabel.textColor = [WebColor black];
        }
    }];
}
// section的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.arrSection.count;
}
// 给section赋值
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    SeekExactReusableView *section = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"xxx" forIndexPath:indexPath];
    section.label.text = self.arrSection[indexPath.section];
    return section;
}
// 每个section的cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSMutableArray *array = [self.dicc objectForKey:[self.arrSection objectAtIndex:section]];
    return array.count;
}
// 给每个section的cell赋值
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    SeekInToCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"xuanche" forIndexPath:indexPath];
    // 找到section对应的cell数组
    NSMutableArray *arr = [self.dicc objectForKey:[self.arrSection objectAtIndex:indexPath.section]];
    // 遍历model
    ExactModel *model = arr[indexPath.row];
    cell.label.text = model.name;
    cell.label.textAlignment = NSTextAlignmentCenter;
    // 首次加载 使4个不限默认选中状态 以后点击哪个cell 哪个就会变蓝 其他是灰色
    for (int i = 0; i < 4; i++) {
        NSIndexPath *ind = self.indexPathArr[i];
        if (ind.section == indexPath.section && ind.row == indexPath.row) {
            cell.label.textColor   = [UIColor blueColor];
            cell.layer.borderWidth = 0.5;
            cell.layer.borderColor = [UIColor blueColor].CGColor;
            break;
        } else {
            cell.label.textColor   = [WebColor black];
            cell.layer.borderWidth = 0.5;
            cell.layer.borderColor = [WebColor gray].CGColor;
        }
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    
    // 刚开始时让button隐藏
    self.button.hidden = NO;
    //记录选择的cell
    [self.indexPathArr replaceObjectAtIndex:indexPath.section withObject:indexPath];
    [self.collectionView reloadData];
    
    switch (indexPath.section) {
        case 0:
        {
            // 存放第0个section对应的cell
            NSMutableArray *arr = [NSMutableArray array];
            arr = [self.dicc objectForKey:[self.arrSection objectAtIndex:indexPath.section]];
            // 遍历数组里存放的model
            ExactModel *model = [arr objectAtIndex:indexPath.row];
            // 判断字典存的value值和对应的value值是否相同
            if ([[_dictionary objectForKey:@"jiage"] isEqualToString:model.value]) {
                // 相同的话 把对应的value值赋空
                [_dictionary setValue:@"" forKey:@"jiage"];
            } else {
                // 不同的话 把value值赋给价格
                [_dictionary setValue:model.value forKey:@"jiage"];
            }
            NSLog(@"%@", _dictionary);
        }
            break;
        case 1:
        {
            NSMutableArray *arr = [NSMutableArray array];
            arr = [self.dicc objectForKey:[self.arrSection objectAtIndex:indexPath.section]];
            ExactModel *model = [arr objectAtIndex:indexPath.row];
            if ([[_dictionary objectForKey:@"jibie"] isEqualToString:model.value]) {
                [_dictionary setValue:@"" forKey:@"jibie"];
            } else {
                [_dictionary setValue:model.value forKey:@"jibie"];
            }
            NSLog(@"%@", _dictionary);
        }
            break;
        case 2:
        {
            NSMutableArray *arr = [NSMutableArray array];
            arr = [self.dicc objectForKey:[self.arrSection objectAtIndex:indexPath.section]];
            ExactModel *model = [arr objectAtIndex:indexPath.row];
            if ([[_dictionary objectForKey:@"pailiang"] isEqualToString:model.value]) {
                [_dictionary setValue:@"" forKey:@"pailiang"];
            } else {
                [_dictionary setValue:model.value forKey:@"pailiang"];
            }
            NSLog(@"%@", _dictionary);
            
        }
            break;
        default:
        {
            NSMutableArray *arr = [NSMutableArray array];
            arr = [self.dicc objectForKey:[self.arrSection objectAtIndex:indexPath.section]];
            ExactModel *model = [arr objectAtIndex:indexPath.row];
            if ([[_dictionary objectForKey:@"biansuxiang"] isEqualToString:model.value]) {
                [_dictionary setValue:@"" forKey:@"biansuxiang"];
            } else {
                [_dictionary setValue:model.value forKey:@"biansuxiang"];
            }
            NSLog(@"%@", _dictionary);
            
        }
            break;
    }
    [self startConnect];
}




/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

@end
